package lib

func init() {
	Probs = append(Probs, Problem{
		Num:         159,
		Discription: "最多存在2个不同字符的最长子数组",
		Level:       1,
		Labels: map[string]int{
			"滑动窗口": 1,
			"哈希表":  1,
		},
	})
}

func LengthOfLongestSubstringTwoDistinct(s string) int {
	left := 0
	right := 1
	chCount := make(map[byte]int, 0)
	differCount := 0
	maxLen := 0
	for right <= len(s) {
		ch := s[right-1]
		chCount[ch]++
		if chCount[ch] == 1 {
			differCount++
			if differCount > 2 {
				//一直删直到不同字符的个数为2
				for differCount > 2 {
					deletedCh := s[left]
					chCount[deletedCh]--
					if chCount[deletedCh] == 0 {
						differCount--
					}
					left++
				}
			}
		}

		maxLen = max(maxLen, right-left)
		right++
	}

	return maxLen
}
